﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.FM
{
    public partial class InvoicePayAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {

                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有未核销发票信息
        /// </summary>
        public void GetInvoiceToAskList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault().Field = "Date";
                }
                if (listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault().Field = "Date";
                }
            }
            else
            {
                SearchCondition search = new SearchCondition();
                search.Field = "State";
                search.Value = "0";
                search.Operator = "=";
                listSearch.Add(search);
            }
            Expression<Func<View_FM_InvoiceList, bool>> exp = SearchExpression.FindByGroup<View_FM_InvoiceList>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            Boolean OrderSort = OperateContext.Order == true ? OperateContext.Order : false;
            if (OperateContext.Sort == null)
            {
                OrderSort = false;
            }
            int count = 0;
            var list = DALSession.Current.View_FM_InvoiceListDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OrderSort);
            count = DALSession.Current.View_FM_InvoiceListDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 获取所有发票回款信息
        /// </summary>
        public void GetRPayListByInvID()
        {
            int invoiceID = Convert.ToInt32(Request["InvoiceID"]);
            var list = DALSession.Current.View_FM_InvoicePayDAL.GetListBy(inP => inP.InvoiceID == invoiceID);
            Response.Write(JsonHelper.toJson(list));
        }

        /// <summary>
        /// 修改发票回款信息
        /// </summary>
        public void EditInvoicePay()
        {
            String msg = "";
            Boolean res = true;
            int ID = Commons.String2Int32(Request.Form["ID"]);
            FM_InvoicePay per = DALSession.Current.FM_InvoicePayDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, per);
            if (checkInvoicePay(per, msg))
            {
                // 检验钩稽金额是否大于回款总金额
                decimal ivTotal = 0;
                var ivlist = DALSession.Current.View_FM_InvoicePayDAL.GetListBy(iP => iP.ReceivePayID == per.ReceivePayID);
                ivlist.ForEach(iv =>
                {
                    if (iv.ID != per.ID)
                    {
                        ivTotal += (decimal)iv.Money;
                    }
                }
                    );
                decimal ivMoney = (decimal)DALSession.Current.FM_ReceivePayDAL.GetListBy(rp => rp.ID == per.ReceivePayID).FirstOrDefault().Money;
                if (ivTotal + per.Money < ivMoney)
                {
                    DALSession.Current.FM_InvoicePayDAL.ModifyAllModel(per);
                    DALSession.Current.FM_InvoiceDAL.SaveChanges();
                    msg = "保存成功！";
                }
                else if (ivTotal + per.Money == ivMoney)
                {
                    DALSession.Current.FM_InvoicePayDAL.ModifyAllModel(per);
                    DALSession.Current.FM_InvoiceDAL.SaveChanges();
                    //更新回款状态
                    DALSession.Current.FM_ReceivePayDAL.GetListBy(r => r.ID == per.ReceivePayID).FirstOrDefault().State = "2";
                    DALSession.Current.FM_ReceivePayDAL.SaveChanges();
                    msg = "保存成功！";
                }
                else
                {
                    res = false;
                    msg = "回款钩稽总金额大于回款总金额，保存失败！";
                }
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 添加回款信息
        /// </summary>
        public void AddInvoicePay()
        {
            Boolean res = true;
            String msg = "";
            try
            {
                FM_InvoicePay per = new FM_InvoicePay();
                ModelTools.Form2EditModel(Request.Form, per);
                if (checkInvoicePay(per, msg))
                {
                    // 检验钩稽金额是否大于回款总金额
                    decimal ivTotal = 0;
                    var ivlist = DALSession.Current.View_FM_InvoicePayDAL.GetListBy(iP => iP.ReceivePayID == per.ReceivePayID);
                    ivlist.ForEach(iv => ivTotal += (decimal)iv.Money);
                    decimal ivMoney = (decimal)DALSession.Current.FM_ReceivePayDAL.GetListBy(rp => rp.ID == per.ReceivePayID).FirstOrDefault().Money;
                    if (ivTotal + per.Money < ivMoney)
                    {
                        DALSession.Current.FM_InvoicePayDAL.Add(per);
                        DALSession.Current.FM_InvoicePayDAL.SaveChanges();
                        //更新发票状态
                        DALSession.Current.FM_InvoiceDAL.GetListBy(i => i.ID == per.InvoiceID).FirstOrDefault().State = "1";
                        DALSession.Current.FM_InvoiceDAL.SaveChanges();
                        //更新回款状态
                        DALSession.Current.FM_ReceivePayDAL.GetListBy(r => r.ID == per.ReceivePayID).FirstOrDefault().State = "1";
                        DALSession.Current.FM_ReceivePayDAL.SaveChanges();
                        msg = "保存成功！";
                    }
                    else if (ivTotal + per.Money == ivMoney)
                    {
                        DALSession.Current.FM_InvoicePayDAL.Add(per);
                        DALSession.Current.FM_InvoicePayDAL.SaveChanges();
                        //更新发票状态
                        DALSession.Current.FM_InvoiceDAL.GetListBy(i => i.ID == per.InvoiceID).FirstOrDefault().State = "1";
                        DALSession.Current.FM_InvoiceDAL.SaveChanges();
                        //更新回款状态
                        DALSession.Current.FM_ReceivePayDAL.GetListBy(r => r.ID == per.ReceivePayID).FirstOrDefault().State = "2";
                        DALSession.Current.FM_ReceivePayDAL.SaveChanges();
                        msg = "保存成功！";
                    }
                    else
                    {
                        res = false;
                        msg = "回款钩稽总金额大于回款总金额，保存失败！";
                    }
                }
                else
                {
                    res = false;
                }
                Response.Write(JsonHelper.toDefaultMsg(res, msg));
            }
            catch (Exception)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "保存失败!"));
            }
        }

        /// <summary>
        /// 删除发票回款信息
        /// </summary>
        public void DelInvoicePay()
        {
            try
            {
                int Id = Convert.ToInt32(Request.Form["Id"].ToString());
                FM_InvoicePay ivPay = DALSession.Current.FM_InvoicePayDAL.GetListBy(iP => iP.ID == Id).FirstOrDefault();
                int invoiceID = ivPay.InvoiceID;
                //更新发票信息
                int iCount = DALSession.Current.FM_InvoicePayDAL.GetCount(iP => iP.InvoiceID == invoiceID&&iP.ID!=Id);
                if (iCount == 0)
                {
                    DALSession.Current.FM_InvoiceDAL.GetListBy(invoice => invoice.ID == invoiceID).FirstOrDefault().State = "0";
                    DALSession.Current.FM_InvoiceDAL.SaveChanges();
                }
                //更新回款信息
                int receivePayID = ivPay.ReceivePayID;
                int rCount = DALSession.Current.FM_InvoicePayDAL.GetCount(iP => iP.ReceivePayID == receivePayID&&iP.ID!=Id);
                if (rCount == 0)
                {
                    DALSession.Current.FM_ReceivePayDAL.GetListBy(rp => rp.ID == receivePayID).FirstOrDefault().State = "0";
                    DALSession.Current.FM_ReceivePayDAL.SaveChanges();
                }
                DALSession.Current.FM_InvoicePayDAL.DelBy(p => p.ID == Id);
                DALSession.Current.FM_InvoicePayDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
            }
            catch (Exception)
            {

                Response.Write(JsonHelper.toDefaultMsg(false, "删除失败"));
            }
        }

        /// <summary>
        /// 校验钩稽实体是否符合要求
        /// </summary>
        /// <param name="iP"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public Boolean checkInvoicePay(FM_InvoicePay iP, String msg)
        {
            Boolean res = true;
            if (String.IsNullOrEmpty(iP.InvoiceID.ToString()))
            {
                res = false;
                msg = "发票ID不能为空！";
            }
            else if (String.IsNullOrEmpty(iP.ReceivePayID.ToString()))
            {
                res = false;
                msg = "回款ID不能为空！";
            }
            else if (String.IsNullOrEmpty(iP.Money.ToString()))
            {
                res = false;
                msg = "钩稽金额不能为空！";
            }
            return res;
        }

    }
}